package app

import (
	"chatgpt/helper/code"
	"chatgpt/logq"
	"chatgpt/model/app"
	"chatgpt/services/datasrv"
	"chatgpt/services/datasrv/sqlhelper"
	"context"
	"github.com/slclub/go-tips"
)

type ScopeSrv struct {
}

func (self *ScopeSrv) GetList(offset, limit int) []*app.Scope {
	if limit == 0 {
		limit = 1000
	}
	datas := self.GetFromDB(&sqlhelper.Where{
		Conds:  []*sqlhelper.CondItem{},
		Order:  "scope_id DESC",
		Offset: offset,
		Limit:  limit,
	})
	if datas == nil {
		return []*app.Scope{}
	}
	return datas
}

func (self *ScopeSrv) GetListWithIDS(ids []int) []*app.Scope {
	datas := self.GetFromDB(&sqlhelper.Where{
		Conds: []*sqlhelper.CondItem{
			sqlhelper.WhereCond("ScopeID", ids, "IN"),
		},
	})
	return datas
}

func (self *ScopeSrv) GetFromDB(where *sqlhelper.Where) []*app.Scope {
	res := sqlhelper.ResWhere{}
	mc := datasrv.AppDB.ScopeSelect(context.Background(), &sqlhelper.ReqWhere{
		Where: where,
	}, &res)
	if res.MsgCode != code.SUCCESS {
		logq.InfoF("ScopeSelect.GET code:%v", mc)
		return nil
	}
	data_arr, ok := res.Data.([]any)
	if !ok {
		return nil
	}

	rtn := []*app.Scope{}
	for _, v := range data_arr {
		m, ok := v.(map[string]any)
		if !ok {
			continue
		}
		tmp := &app.Scope{}
		tmp.ConvFromMap(m)
		rtn = append(rtn, tmp)
	}
	return rtn
}

func (self *ScopeSrv) Save(bs *app.Scope) code.CODENO {
	res := sqlhelper.ResWhere{}
	mc := datasrv.AppDB.ScopeSave(context.Background(), &sqlhelper.ReqWhere{
		Object: bs.ConvToMap(),
		Where: &sqlhelper.Where{
			Conds: []*sqlhelper.CondItem{
				sqlhelper.WhereCond("ScopeID", bs.ScopeID),
			},
			Formula: "{1}",
		},
	}, &res)
	if res.MsgCode == 0 {
		res.MsgCode = mc
	}
	if res.MsgCode != code.SUCCESS {
		logq.InfoF("ScopeSrv.Save code:%v", mc)
		return res.MsgCode
	}
	bs.ConvFromMap(res.Data.(map[string]any))
	return code.SUCCESS
}

func (self *ScopeSrv) Total(where *sqlhelper.Where) int {
	res := sqlhelper.ResWhere{}
	mc := datasrv.AppDB.ScopeTotal(context.Background(), &sqlhelper.ReqWhere{
		Where: where,
	}, &res)
	if res.MsgCode != code.SUCCESS {
		logq.InfoF("ScopeSrv.Total code:%v", mc)
		return 0
	}
	return tips.Int(res.Data)
}
